<?php

namespace app\admin\controller;

use app\admin\model\Node;
use app\admin\model\Role;
use app\admin\controller\Base;
use app\admin\model\Role_node;
use app\admin\model\User_role;
use think\Request;

class Roles extends Base
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {

        $list = Role::all();
        $data = [];
        foreach ($list as $val){
            $data[] = $val->getData();
        }
        return view('role/index', ['data'=>$data]);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {

        $list = Node::all();
        $data = [];
        foreach ($list as $val){
            $data[] = $val->getData();
        }
        return view('role/add', ['data'=>$data]);
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $info = input('post.');
        $data['name'] = $info['name'];
        $data['status'] = $info['status'];
        $data['remark'] = $info['remark'];
        $result = Role::create($data)->getData();
        $node = new Role_node();
        $node->add($result['id'],$info['node']);
        $data = [];
        if ($result['id']>0){
            $data['status'] = true;
            $data['message'] = '添加成功';
        }else{
            $data['status'] = false;
            $data['message'] = '添加失败';
        }
        return json($data);
    }


    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        $data = input('put.');
        $role = Role::get($id);
        $role->name = $data['name'];
        $role->status = $data['status'];
        $role->remark = $data['remark'];
        $result = $role->save();
        $data = [];
        if ($result>0){
            $data['status'] = true;
            $data['message'] = '添加成功';
        }else{
            $data['status'] = false;
            $data['message'] = '添加失败';
        }
        return json($data);
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $role =  Role::get($id);
        $result = $role->delete();
        User_role::where('rid', '=', $id)->delete();
        Role_node::where('rid', '=', $id)->delete();

        $data = [];
        if ($result>0){
            $data['status'] = true;
            $data['message'] = '删除成功';
        }else{
            $data['status'] = false;
            $data['message'] = '删除失败';
        }
        return json($data);
    }
}
